<template>
  <div class="container p-6">
    <!-- 搜索区域 -->
    <div class="mb-4 flex items-center space-x-4">
      <el-input
        v-model="searchParams.title"
        placeholder="考试名称"
        class="!w-[200px]"
        clearable
        @input="handleAutoSearch"
        @clear="handleAutoSearch"
      />
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column
        prop="title"
        label="试卷名称"
        min-width="140"
        align="center"
      />
      <el-table-column
        prop="examDuration"
        label="考试时间"
        min-width="100"
        align="center"
      />
      <el-table-column
        prop="maxCount"
        label="最多切屏次数"
        min-width="120"
        align="center"
      />

      <el-table-column
        prop="grossScore"
        label="总分"
        min-width="120"
        align="center"
      />
      <el-table-column
        prop="passedScore"
        label="及格分"
        min-width="80"
        align="center"
      />
      <el-table-column
        prop="startTime"
        label="开始时间"
        min-width="160"
        align="center"
      />
      <el-table-column
        prop="endTime"
        label="结束时间"
        min-width="160"
        align="center"
      />
      <el-table-column label="操作" fixed="right" width="180" align="center">
        <template #default="scope">
          <el-button type="success" link @click="handleView(scope.row)">
            查看
          </el-button>
          <el-button type="primary" link @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="mt-4 flex items-center text-sm text-gray-500">
      <span>共 {{ searchParams.total }} 条</span>
      <div class="ml-4 flex items-center">
        <el-select
          v-model="searchParams.pageSize"
          class="!w-[100px] mr-2"
          @change="handleSizeChange"
        >
          <el-option
            v-for="size in [10, 20, 30, 50]"
            :key="size"
            :label="`${size}条/页`"
            :value="size"
          />
        </el-select>
        <el-pagination
          v-model:current-page="searchParams.pageNum"
          :page-size="searchParams.pageSize"
          layout="prev, pager, next"
          :total="searchParams.total"
          :pager-count="5"
          background
          @current-change="handleCurrentChange"
        />
        <span class="mx-2">前往</span>
        <el-input
          v-model="jumpPage"
          class="!w-[50px]"
          @keyup.enter="handleJumpPage"
        />
        <span class="mx-2">页</span>
      </div>
    </div>

    <!-- 编辑试卷侧边栏 -->
    <el-drawer
      v-model="editDialogVisible"
      :title="isViewMode ? '查看试卷' : '编辑试卷'"
      :modal="true"
      size="350px"
      :close-on-click-modal="false"
      direction="rtl"
      destroy-on-close
    >
      <template #default>
        <el-form
          ref="editFormRef"
          :model="editForm"
          :rules="rules"
          label-width="120px"
          class="drawer-form"
          :disabled="isViewMode"
        >
          <el-form-item label="试卷标题" prop="title">
            <el-input v-model="editForm.title" placeholder="请输入试卷标题" />
          </el-form-item>
          <el-form-item label="考试时长" prop="examTime">
            <el-input-number v-model="editForm.examTime" :min="1" :max="180" />
          </el-form-item>
          <el-form-item label="最大切屏次数" prop="maxSwitchCount">
            <el-input-number
              v-model="editForm.maxSwitchCount"
              :min="0"
              :max="100"
            />
          </el-form-item>
          <el-form-item label="及格分" prop="passScore">
            <el-input-number v-model="editForm.passScore" :min="1" :max="100" />
          </el-form-item>
          <el-form-item label="单选题分数" prop="singleChoiceScore">
            <el-input-number
              v-model="editForm.singleChoiceScore"
              :min="0"
              :max="100"
            />
          </el-form-item>
          <el-form-item label="多选题分数" prop="multiChoiceScore">
            <el-input-number
              v-model="editForm.multiChoiceScore"
              :min="0"
              :max="100"
            />
          </el-form-item>
          <el-form-item label="判断题分数" prop="judgeScore">
            <el-input-number
              v-model="editForm.judgeScore"
              :min="0"
              :max="100"
            />
          </el-form-item>
          <el-form-item label="简答题分数" prop="shortAnswerScore">
            <el-input-number
              v-model="editForm.shortAnswerScore"
              :min="0"
              :max="100"
            />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div class="drawer-footer">
          <el-button @click="editDialogVisible = false">
            {{ isViewMode ? '关闭' : '取消' }}
          </el-button>
          <el-button v-if="!isViewMode" type="primary" @click="submitEditForm"
            >确定</el-button
          >
        </div>
      </template>
    </el-drawer>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="考试详情"
      width="700px"
      align-center
      destroy-on-close
    >
      <div class="detail-container">
        <table class="detail-table">
          <tbody>
            <tr>
              <td class="detail-label">考试标题：</td>
              <td class="detail-value">{{ detailData.title }}</td>
              <td class="detail-label">考试时长：</td>
              <td class="detail-value">{{ detailData.examDuration }} 分钟</td>
            </tr>
            <tr>
              <td class="detail-label">最大切屏次数：</td>
              <td class="detail-value">{{ detailData.maxCount }}</td>
              <td class="detail-label">及格分：</td>
              <td class="detail-value">{{ detailData.passedScore }}</td>
            </tr>
            <tr>
              <td class="detail-label">单选题数量：</td>
              <td class="detail-value">
                {{ detailData.singleChoiceCount || 0 }}
              </td>
              <td class="detail-label">单选题分数：</td>
              <td class="detail-value">
                {{ detailData.singleChoiceScore || 0 }}
              </td>
            </tr>
            <tr>
              <td class="detail-label">多选题数量：</td>
              <td class="detail-value">
                {{ detailData.multiChoiceCount || 0 }}
              </td>
              <td class="detail-label">多选题分数：</td>
              <td class="detail-value">
                {{ detailData.multiChoiceScore || 0 }}
              </td>
            </tr>
            <tr>
              <td class="detail-label">判断题数量：</td>
              <td class="detail-value">{{ detailData.judgeCount || 0 }}</td>
              <td class="detail-label">判断题分数：</td>
              <td class="detail-value">{{ detailData.judgeScore || 0 }}</td>
            </tr>
            <tr>
              <td class="detail-label">简答题数量：</td>
              <td class="detail-value">
                {{ detailData.shortAnswerCount || 0 }}
              </td>
              <td class="detail-label">简答题分数：</td>
              <td class="detail-value">
                {{ detailData.shortAnswerScore || 0 }}
              </td>
            </tr>
          </tbody>
        </table>

        <div class="mt-4">
          <div class="time-range-title">考试时间范围</div>
          <table class="detail-table">
            <tbody>
              <tr>
                <td class="detail-label">开始时间：</td>
                <td class="detail-value">{{ detailData.startTime }}</td>
                <td class="detail-label">结束时间：</td>
                <td class="detail-value">{{ detailData.endTime }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getExamlist } from '@/api/teacher/exam'

// 防抖定时器
let searchTimer = null

// 路由
const router = useRouter()

// 表格数据
const tableData = ref([])

// 分页相关
const searchParams = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 5,
  title: '',
})

// 选中的行
const selectedRows = ref([])

// 编辑弹窗显示控制
const editDialogVisible = ref(false)
const currentEditId = ref('')
// 弹窗模式：edit-编辑，view-查看
const dialogMode = ref('edit')
const isViewMode = computed(() => dialogMode.value === 'view')
// 编辑表单ref
const editFormRef = ref()

// 编辑表单数据
const editForm = reactive({
  title: '',
  examTime: 60,
  maxSwitchCount: 10,
  passScore: 60,
  singleChoiceScore: 10,
  multiChoiceScore: 0,
  judgeScore: 0,
  shortAnswerScore: 0,
  startTime: '',
  endTime: '',
})

// 详情弹窗
const detailDialogVisible = ref(false)
const detailData = ref({})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入试卷标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  examTime: [{ required: true, message: '请输入考试时长', trigger: 'blur' }],
  maxSwitchCount: [
    { required: true, message: '请输入最大切屏次数', trigger: 'blur' },
  ],
  passScore: [{ required: true, message: '请输入及格分', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
}

// 获取试卷列表
const getExamList = async () => {
  // 模拟API调用
  // 实际项目中应该调用后端API
  const { data } = await getExamlist(searchParams)
  tableData.value = data.records
  searchParams.total = data.total
  searchParams.pageNum = data.current
  searchParams.pageSize = data.size

  // 模拟搜索功能
  if (searchParams.title) {
    tableData.value = tableData.value.filter((item) =>
      item.title.includes(searchParams.title)
    )
    searchParams.total = tableData.value.length
  }
}

// 处理查看
const handleView = (row) => {
  // 显示详情对话框
  detailDialogVisible.value = true

  // 填充详情数据
  detailData.value = { ...row }

  // 查询更完整的详情数据（实际项目中可能需要额外请求）
  // getExamDetail(row.id).then(res => {
  //   detailData.value = { ...row, ...res.data }
  // })
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该试卷吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 模拟删除成功
      tableData.value = tableData.value.filter((item) => item.id !== row.id)
      searchParams.total = tableData.value.length
      ElMessage.success('删除成功')
    })
    .catch(() => {
      // 取消删除
    })
}

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  searchParams.pageSize = val
  getExamList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  searchParams.pageNum = val
  getExamList()
}

// 处理跳转页码
const jumpPage = ref('')
const handleJumpPage = () => {
  searchParams.pageNum = Number(jumpPage.value)
  getExamList()
}

// 打开添加页面
const handleAdd = () => {
  router.push('/teacher/addexam')
}

// 处理编辑
const handleEdit = (row) => {
  // 显示抽屉，设置为编辑模式
  editDialogVisible.value = true
  dialogMode.value = 'edit'
  currentEditId.value = row.id

  // 重置表单验证状态
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }

  // 填充表单数据
  Object.assign(editForm, row)
}

// 提交编辑表单
const submitEditForm = async () => {
  if (!editFormRef.value) return

  await editFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      // 模拟编辑成功
      const index = tableData.value.findIndex(
        (item) => item.id === currentEditId.value
      )
      if (index !== -1) {
        tableData.value[index] = {
          ...tableData.value[index],
          ...editForm,
        }
      }
      ElMessage.success('编辑成功')
      editDialogVisible.value = false
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 自动搜索处理函数（添加防抖）
const handleAutoSearch = () => {
  // 清除之前的定时器
  if (searchTimer) {
    clearTimeout(searchTimer)
  }

  // 设置新的定时器，延迟300ms执行搜索
  searchTimer = setTimeout(() => {
    getExamList()
  }, 300)
}

// 挂载
onMounted(() => {
  // 获取试卷列表
  getExamList()
})
</script>

<style lang="less" scoped>
.container {
  background-color: white;
  border-radius: 8px;
  min-height: calc(100vh - 120px);
}

:deep(.el-table) {
  .cell {
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
  }

  .el-table__header th {
    .cell {
      justify-content: center;
    }
  }

  .el-button {
    margin: 0 auto;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 分页样式
:deep(.el-pagination) {
  .el-pagination__total {
    margin-right: 16px;
  }

  .el-pagination__sizes {
    margin-right: 16px;
  }

  .el-pager li {
    background-color: transparent;

    &.is-active {
      background-color: var(--el-color-primary);
      color: white;
    }
  }

  .btn-prev,
  .btn-next {
    background-color: transparent;
  }

  .el-input__inner {
    text-align: center;
    padding: 0 5px;
  }
}

// 下拉选择框样式
:deep(.el-select) {
  .el-input__wrapper {
    background-color: transparent;
  }
}

:deep(.el-form) {
  .el-form-item {
    margin-bottom: 20px;
  }
}

// 抽屉表单样式
:deep(.el-drawer__body) {
  padding: 20px;

  .drawer-form {
    height: calc(100% - 60px);
    overflow-y: auto;
  }
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px;
  background: white;
  border-top: 1px solid var(--el-border-color-lighter);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 详情样式
.detail-container {
  padding: 16px;
}

.detail-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #ebeef5;
  margin-bottom: 16px;
}

.detail-table td {
  padding: 12px;
  border: 1px solid #ebeef5;
  line-height: 1.5;
}

.detail-label {
  width: 25%;
  color: #606266;
  font-weight: 500;
  background-color: #f5f7fa;
  text-align: right;
}

.detail-value {
  width: 25%;
  color: #303133;
}

.time-range-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}
</style>
